<template>
  <div class="preview-section">
    <div class="preview-grid">
      <div
        class="preview-item"
        v-for="(file, index) in originFiles"
        :key="index">
        <div class="image-box">
          <img :src="file.url" class="preview-img" />
          <div
            class="delete-btn"
            @click="removeOriginImage(file.id, index)"
            title="删除图片">
            ×
          </div>
        </div>
      </div>
      <!-- 已选图片列表 -->
      <div
        class="preview-item"
        v-for="(file, index) in uploader.filesInfo"
        :key="index">
        <div class="image-box">
          <img
            :src="file.previewUrl"
            :alt="file.fileName"
            class="preview-img" />
          <button
            class="delete-btn"
            @click="removeImage(index)"
            title="删除图片">
            ×
          </button>
        </div>
        <!-- <div class="file-meta">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-size">{{ formatFileSize(file.fileSize) }}</div>
              </div> -->
        <div v-if="file.error" class="error-message">{{ file.error }}</div>
      </div>

      <!-- 上传占位框 -->
      <div class="upload-placeholder" @click="openFileSelector">
        <div class="placeholder-content">
          <input
            type="file"
            ref="fileInput"
            class="file-input"
            multiple
            accept="image/*"
            @change="handleFileSelect" />
          <i class="upload-icon">+</i>
          <p>点击此处上传</p>
          <p class="support-text">支持JPG、PNG格式，</p>
          <p class="size-text">单张不超过2M</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import FileUploadUtil from "@/utils/uploadv3.js"; // 替换为实际工具类路径
import axios from "axios";
import { getToken } from "@/utils/auth.js";
export default {
  data() {
    return {
      uploader: new FileUploadUtil(),
    };
  },
  props: {
    originFiles: {
      type: Array,
      default: () => [],
    },
    skuId: {
      type: Number,
    },
  },
  methods: {
    // 打开文件选择器
    openFileSelector() {
      this.$refs.fileInput.click();
    },

    // 处理文件选择（通过隐藏的input）
    handleFileSelect(e) {
      const files = e.target.files;
      if (files && files.length) {
        this.processFiles(files);
      }
      e.target.value = ""; // 重置input，允许重复选同文件
    },

    // 处理选中的文件
    processFiles(files) {
      // 过滤出图片文件（仅JPG/PNG）
      const imageFiles = Array.from(files).filter(
        (file) => file.type === "image/jpeg" || file.type === "image/png"
      );

      // 逐个处理文件（工具类验证尺寸/类型）
      imageFiles.forEach((file) => {
        this.uploader.handleFileUpload(file, {
          acceptTypes: ["image/jpeg", "image/png"],
          maxSize: 2 * 1024 * 1024, // 2MB
        });
      });
    },

    // 移除指定索引的图片
    removeImage(index) {
      this.uploader.removeFile(index);
    },

    // 上传所有图片到服务器
    async uploadAllImages() {
      try {
        // 示例：上传到服务器，实际项目中替换为真实URL
        console.log(this.uploader.filesInfo, "这是上传的文件信息");
        const response = await this.uploader.uploadToServer(
          "http://47.112.187.193:8092/product/productImage/upload",
          { skuId: this.skuId }
        );
        console.log("上传成功", response);
        return response; // 返回结果供外部使用
      } catch (error) {
        console.error("上传失败", error); // 建议用error级别日志
        // 错误信息处理更健壮，避免error可能没有message属性的情况
        alert(error?.message || "图片上传失败，请稍后重试");
        throw error; // 抛出错误供外部捕获处理（可选，根据业务需求）
      }
    },

    // 清空所有图片
    clearAllImages() {
      while (this.uploader.filesInfo.length > 0) {
        this.uploader.removeFile(0);
      }
    },

    // 格式化文件大小
    formatFileSize(size) {
      return this.uploader.formatFileSize(size);
    },
    removeOriginImage(imageId, index) {
      console.log(imageId, index, "删除图片");
      axios
        .delete(
          `http://47.112.187.193:8092/product/productImage/delete/${imageId}`,
          {
            headers: {
              Authorization: "Bearer " + getToken(),
            },
          }
        )
        .then((response) => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.originFiles.splice(index, 1);
        })
        .catch((error) => {
          console.error("删除失败", error);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
// 预览区域
.preview-section {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  // 水平滚动容器
  .preview-grid {
    display: flex;
    flex-wrap: wrap; // 强制不换行，水平排列
    gap: 16px;
    padding-bottom: 10px; // 滚动条下方间距
  }

  // 图片项 + 上传占位框 公共样式
  .preview-item,
  .upload-placeholder {
    width: 180px; // 每个项的宽度
    flex-shrink: 0; // 禁止缩小，保持宽度
    border-radius: 6px;
    overflow: hidden;
    margin-right: 15px;
    margin-bottom: 15px;
  }

  // 已选图片项样式
  .preview-item {
    display: flex;
    flex-direction: column;
    border: 1px solid #eee;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    .image-box {
      position: relative;
      height: 100%; // 图片区域高度
      overflow: hidden;

      .preview-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.05);
        }
      }

      .delete-btn {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: rgba(255, 0, 0, 0.8);
        color: white;
        border: none;
        cursor: pointer;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: all 0.3s ease;

        &:hover {
          background-color: rgba(255, 0, 0, 1);
        }
      }

      &:hover .delete-btn {
        opacity: 1;
      }
    }

    .error-message {
      padding: 6px 8px;
      font-size: 12px;
      color: #f5222d;
      background-color: #fff1f0;
    }
  }

  // 上传占位框样式
  .upload-placeholder {
    height: 180px; // 与预览项整体高度一致
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    cursor: pointer;
    border: 1px dashed #d0d7de; // 虚线边框
    transition: all 0.3s ease;

    &:hover {
      border-color: #4096ff;
      background-color: #f0f7ff;
    }

    .placeholder-content {
      //   padding: 10px;

      .upload-icon {
        font-size: 24px;
        color: #888;
        margin-bottom: 8px;
        display: block;
      }

      p {
        margin: 4px 0;
        font-size: 14px;
        color: #666;
      }

      .support-text,
      .size-text {
        font-size: 12px;
      }
    }
  }
}

// 上传按钮
.upload-btn {
  margin-top: 25px;
  padding: 10px 20px;
  background-color: #4096ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;

  &:hover {
    background-color: #1890ff;
  }

  &:disabled {
    background-color: #ccc;
    cursor: not-allowed;
    opacity: 0.7;
  }
}

// 隐藏的文件选择器（通过上传占位框触发）
.file-input {
  display: none;
}
</style>
